import { useGlobalStore } from '@/stores/global'
import { useRouter, type RouteLocationRaw } from 'vue-router'
interface MircoApp {
  name: string // 子应用名称
  port: number // 子应用本地运行的端口号
  origin?: string // 非科创空间服务器下的远程应用域名
}

// 这里注册子应用，子应用端口8101-8198，注意新增时候不要重复
const apps: Array<MircoApp> = [
  {
    name: 'systemset',
    port: 8578
  },
  {
    // 流程表单管理
    name: 'workflow',
    port: 8501
  }
  // 远程子应用示例
  // {
  //   name: 'origin-app',
  //   port: 8198,
  //   origin: import.meta.env.VITE_ORIGIN_HOST
  // }
]

const initMicroApps = () => {
  const store = useGlobalStore()
  const router = useRouter()
  return apps.map(({ name, port, origin }) => {
    const host = origin ? `${origin}/${name}/` : `/apps/${name}/`
    const path = `/${name}`
    const entry = process.env.NODE_ENV === 'production'? host : `http://127.0.0.1:${port}/${name}/`
    console.log(entry, 'app')
    return {
      name,
      entry,
      activeRule: () => window.location.pathname.startsWith(path),
      container: '#main-frame', // 子应用挂载的div
      props: {
        routerBase: path, // 下发基础路由
        mainStore: store, // 主应用store
        mainRouterPush: (args: RouteLocationRaw) => {
          const { pathname, search } = window.location
          Object.assign(history.state, { current: `${pathname}${search}` })
          // 全局路由跳转方法封装
          router.push(args)
          // const resolvePath = router.resolve(args) // 参数处理
          // Object.assign(history.state, { current: route.fullPath })
        },
        mainRouter: router
      }
    }
  })
}

export {
  apps,
  initMicroApps
}